package lumis.service.newsletter;

import java.util.Collection;

import lumis.content.source.dataprovider.ContentServicesDataProvider;
import lumis.doui.source.ISourceData;
import lumis.doui.source.TabularData;
import lumis.doui.source.TabularSource;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.localization.ILocalizationManager;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.service.ServiceConfig;
import lumis.util.IResource;
import lumis.util.ITransaction;

/**
 * Provides data about content Instantiated and Instantiable services.
 *
 * @version $Revision: 8517 $ $Date: 2007-11-12 16:37:05 -0200 (Mon, 12 Nov 2007) $
 * @since 4.0.11
 */
public class ContentInstantiatedServicesDataProvider extends ContentServicesDataProvider
{

	@Override
	public void loadData(SessionConfig sessionConfig, TabularSource<?> source, ITransaction transaction) throws PortalException
	{
		Collection<ServiceConfig> serviceConfigs = getServiceConfigs(sessionConfig, transaction);

		String searchValue = (String)source.getParameterValue("filterName");

		ILocalizationManager localizationManager = ManagerFactory.getLocalizationManager();
		IResource resource;

		TabularData tabularData = source.getData();
		for (ServiceConfig serviceConfig : serviceConfigs)
		{
			// get only instancied services.
			Collection<String> ids = ManagerFactory.getServiceInstanceManager().getIdsByServiceId(sessionConfig, serviceConfig.getId(), transaction);
			if(ids != null && ids.size()>0)
			{
				resource = serviceConfig.getResource();
				String name = localizationManager.localize(serviceConfig.getName(), resource);
				String description = localizationManager.localize(serviceConfig.getDescription(), resource);
	
				if (searchValue != null)
				{
					if (name.toLowerCase().indexOf(searchValue.toLowerCase()) == -1 && description.toLowerCase().indexOf(searchValue.toLowerCase()) == -1)
						continue;
				}
				
				ISourceData sourceData = tabularData.addRow();
				sourceData.put("id", serviceConfig.getId());
				sourceData.put("name", name);
				sourceData.put("description", description);
				sourceData.put("image", serviceConfig.getImage());
			}
		}
		
		tabularData.sort(source);
	}
	
}
